var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};

const hostname = '127.0.0.1';
const port = 3000;

/**
 * 请求不存在时，发送404错误
 * @param {*} response 
 */
function send404(response) {
    response.writeHead(404, {'Content-Type': 'text/plain'});
    response.write('Error 404: resource not found.');
    response.end();
}

/**
 * 发送文件
 * @param {*} response 
 * @param {*} filePath 
 * @param {*} fileContents 
 */
function sendFile(response, filePath, fileContents) {
    response.writeHead(200, 
        {"Content-type": mime.lookup(path.basename(filePath))}
    );
    response.end(fileContents);
}

/**
 * 静态资源查找
 * @param {*} response 
 * @param {*} cache 
 * @param {*} absPath 
 */
function serverStatic(response, cache, absPath) {
    if (cache[absPath]) {
        sendFile(response, absPath, cache[absPath]);
    } else {
        if (fs.existsSync(absPath)) {
            fs.readFile(absPath, function(err, data) {
                if (err) {
                    send404(response);
                } else {
                    cache[absPath] = data;
                    sendFile(response, absPath, data);
                }
            });
        } else {
            send404(response);
        }
    }
}

var server = http.createServer(function(request, response) {
    var filePath = false;
    if (request.url == '/') {
        filePath = 'public/index.html';
    } else {
        filePath = 'public' + request.url;
    }
    var absPath = './' + filePath;
    serverStatic(response, cache, absPath);
});

server.listen(port, hostname, () => {
	console.log(`Server running at http://${hostname}:${port}/`)
});

var chatServer = require('./lib/chat_server');//加载自定义模块
chatServer.listen(server);